package com.example.demo.interceptor;

import com.example.demo.exception.BusinessException;
import com.example.demo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class BlacklistInterceptor implements HandlerInterceptor {

    private static final String BLACKLIST_KEY_PREFIX = "blacklist:user:";
    private static final long BLACKLIST_TIME_MINUTES = 10; // 黑名单持续时间，这里设置为10分钟
    private static final int REQUEST_LIMIT = 10; // 10秒内请求次数限制


    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userKey = getUserKey(request); // 根据实际情况获取用户标识，例如IP地址或用户ID
        if (isBlacklisted(userKey)) {
            // 如果已经在黑名单中，直接拒绝访问
            throw new BusinessException("点太快了");
        }

        // 检查请求频率
        Long count = redisUtil.increment(userKey + ":reqCount", 1);
        if (count > REQUEST_LIMIT) {
            // 达到请求限制，加入黑名单
            throw new BusinessException("点太快了");
        }

        // 清理过期的请求计数
//        cleanExpiredRequests(userKey);

        return true;
    }

    private String getUserKey(HttpServletRequest request) {
        // 实现逻辑根据实际情况获取用户标识，比如用IP地址举例：
        return BLACKLIST_KEY_PREFIX + request.getRemoteAddr();
    }

    private boolean isBlacklisted(String userKey) {
        return Boolean.TRUE.equals(redisUtil.hasKey(userKey));
    }

    private void addBlacklist(String userKey) {
        redisUtil.set(userKey, "true", BLACKLIST_TIME_MINUTES, TimeUnit.MINUTES);
    }


}